package com.supreme.secretserver.secret;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.supreme.secretserver.utils.RSAUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
@Qualifier(value = "rsaSecretParser")
public class RSASecretParser implements SecretParser {

    @Override
    public InputStream buildStringInputStream(String bodyString, String decryptKey, byte[] secretBytes) throws Exception {
        List<String> decryptBodyList = new ArrayList<>();
        String decodeBodyContent = URLDecoder.decode(bodyString, StandardCharsets.UTF_8.name());
        String[] parameter = StringUtils.split(decodeBodyContent, "&");
        for (String paraItem : parameter) {
            final String[] paraArray = StringUtils.split(paraItem, "=");
            final String itemKey = paraArray[0];
            final String itemVal = paraArray[1];

            if (itemKey.equals(decryptKey)) {
                String decryptData = RSAUtils.decryptByPrivateKey(secretBytes, itemVal.getBytes());
                decryptBodyList.add(String.format("%s=%s", itemKey, decryptData));
            } else {
                decryptBodyList.add(paraItem);
            }
        }

        byte[] bytes = StringUtils.join(decryptBodyList, "&").getBytes();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        return byteArrayInputStream;
    }

    @Override
    public InputStream buildJsonInputStream(byte[] bodyBytes, ObjectMapper objectMapper, String decryptKey, byte[] secretBytes) throws Exception {
        JSONObject bodyJson = objectMapper.readValue(bodyBytes, JSONObject.class);
        if (bodyJson.containsKey(decryptKey)) {
            String encryptPayload = bodyJson.getStr(decryptKey);
            String decryptData = RSAUtils.decryptByPrivateKey(secretBytes, encryptPayload.getBytes());
            bodyJson.set(decryptKey, decryptData);
        }

        byte[] bytes = objectMapper.writeValueAsBytes(bodyJson);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        return byteArrayInputStream;
    }
}
